﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web;
using System.Xml.Linq;

namespace CloudAppRestDemoWeb.Pages {

  public class appWebTitle : IHttpHandler {

    public void ProcessRequest(HttpContext context) {

      // retrieve app web url from cache
      string appWebUrl = context.Cache["SPAppWebUrl"].ToString();
  
      Uri uri = new Uri(appWebUrl + "/_api/web/?$select=Title");
      HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(uri);
      requestGet.Credentials = CredentialCache.DefaultCredentials;
      requestGet.Method = "GET";
      HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();
      XDocument doc = XDocument.Load(responseGet.GetResponseStream());
      XNamespace ns_dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";
      string appWebTitleREST = doc.Descendants(ns_dataservices + "Title").First().Value;
      // display Title property on page
      
      
      context.Response.ContentType = "text/plain";
      context.Response.Write(appWebTitleREST);
    }

    public bool IsReusable {
      get {
        return false;
      }
    }
  }
}